﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace miniQQ_CSharp_SDK
{
    public static class JsonLinqExt
    {
        /// <summary>
        /// 向 JObject 中添加 object 类型
        /// </summary>
        /// <param name="_jobj">JObject自身</param>
        /// <param name="_name">object需要设置的key</param>
        /// <param name="_obj">object对象</param>
        public static void Add(this JObject _jobj, string _name, object _obj)
        {
            _jobj.Add(_name, JToken.FromObject(_obj));
        }

        /// <summary>
        /// 取出 JObject 中的 object 对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="_jObj">JObject</param>
        /// <param name="_keyName">对象的keyName</param>
        /// <param name="_obj">object对象</param>
        /// <returns></returns>
        public static bool TryGetValue<T>(this JObject _jObj, string _keyName, out T _obj)
        {
            _obj = default;
            // 通过需要的参数类型名, 拿到 _jObj 中相应的 value 
            if (_jObj.TryGetValue(_keyName, out JToken jToken))
            {
                if (typeof(T).IsValueType)
                {
                    _obj = jToken.Value<T>();
                }
                else
                {
                    _obj = jToken.ToObject<T>();
                }
                return true;
            }

            return false;
        }
    }
}
